
"""
    :copyright: © 2019 by the Lin team.
    :license: MIT, see LICENSE for more details.
"""

from lin.redprint import Redprint
from lin import login_required
from lin.exception import Success, Failed
from flask import jsonify
from .model import my_product
from .forms import PosionSearchForm, ProductSearchForm
from .forms import CreateOrUpdateProductForm, CreateOrUpdatePosionForm, CreateOrUpdateProductRepayForm, CreateOrUpdateMandatorForm

product_api = Redprint("product")


@product_api.route("/<psn>", methods=["GET"])
@login_required
def get_product_by_sn(psn):
    product = my_product.get_product_by_sn(psn)
    return jsonify(product)


@product_api.route("/page=<page>", methods=["GET"])
@login_required
def get_all_products(page):
    products = my_product.get_all_products(page)
    return jsonify(products)


@product_api.route("/info/<psn>", methods=["GET"])
@login_required
def get_product_info(psn):
    info = my_product.get_product_info(psn)
    return jsonify(info)


@product_api.route("/repay/<psn>", methods=["GET"])
@login_required
def get_product_repay(psn):
    repay = my_product.get_product_repay(psn)
    return jsonify(repay)


@product_api.route("/search", methods=["GET"])
@login_required
def get_product_by_name():
    form = PosionSearchForm().validate_for_api()
    _res = my_product.get_product_by_name(form.q.data)
    return jsonify(_res)


@product_api.route("/posion/psn=<psn>&page=<page>", methods=["GET"])
@login_required
def get_product_posion(psn, page):
    _posion = my_product.get_posion_by_product(psn, page)
    return jsonify(_posion)


@product_api.route("/<psn>", methods=["POST"])
@login_required
def update_product(psn):
    form = CreateOrUpdateProductForm().validate_for_api()
    my_product.update_product(psn, form)
    return Success('产品信息更新成功')


@product_api.route("/mandator", methods=["GET"])
@login_required
def get_mandator():
    _man = my_product.get_madater()
    return jsonify(_man)


@product_api.route("/brokerage", methods=["GET"])
@login_required
def get_brokerage():
    _bro = my_product.get_broker()
    return jsonify(_bro)